//
//  ManAddTicketVC.swift
//  ManGuangDB
//
//  Created by 李东 on 2024/3/26.
//

import UIKit
import UniformTypeIdentifiers
class ManAddTicketVC: ManBaseVC {
    
    @IBOutlet weak var picBtn: UIButton!
    @IBOutlet weak var titleTF: UITextField!
    @IBOutlet weak var timeTF: UITextField!
    @IBOutlet weak var placeTF: UITextField!
    @IBOutlet weak var paternerTF: UITextField!
    @IBOutlet weak var remarkTF: UITextField!
    
    @IBOutlet weak var timeView: UIView!
    
    @IBOutlet weak var deleteBtn: UIButton!
    
    var model = ManTicketModel()
    
    init(model: ManTicketModel = ManTicketModel()) {
        super.init(nibName: nil, bundle: nil)
        self.model = model
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "珍贵票票"
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_finish")?.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(finishHandle))
        timeTF.isEnabled = false
        timeView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectDateAndTime)))
        titleTF.attributedPlaceholder = NSAttributedString(string: "请输入主题内容", attributes: [.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
        timeTF.attributedPlaceholder = NSAttributedString(string: "请选择时间", attributes: [.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
        placeTF.attributedPlaceholder = NSAttributedString(string: "请输入地点", attributes: [.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
        paternerTF.attributedPlaceholder = NSAttributedString(string: "请输入文字内容", attributes: [.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
        remarkTF.attributedPlaceholder = NSAttributedString(string: "添加备注", attributes: [.foregroundColor: UIColor.white.withAlphaComponent(0.5)])
        if model.ids != 0 {
            titleTF.text = model.title
            timeTF.text = ManDataHelper.shared.df1.string(from: Date(timeIntervalSince1970: TimeInterval(model.ts)))
            placeTF.text = model.place
            paternerTF.text = model.paterner
            remarkTF.text = model.remark
            picBtn.setImage(UIImage(contentsOfFile: CompressedHelper.shared.getFilePath(fileName: model.fileName)), for: .normal)
            deleteBtn.isHidden = false
        }
    }
    
    @objc func finishHandle() {
        if model.fileName.isEmpty {
            showHUDTextOnly("请上传珍贵票票图片")
            return
        }
        if titleTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入主题内容")
            return
        }
        if timeTF.text?.isEmpty ?? true {
            showHUDTextOnly("请选择时间")
            return
        }
        if placeTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入地点")
            return
        }
        if model.ids == 0 {
            model.ids = Int(Date().timeIntervalSince1970)
        }
        model.title = titleTF.text ?? ""
        model.place = placeTF.text ?? ""
        model.paterner = paternerTF.text ?? ""
        model.remark = remarkTF.text ?? ""
        ManDataHelper.shared.addData(model: model)
        showHUDTextOnly("保存成功") {[weak self] in
            guard let self = self else {
                return
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func selectDateAndTime() {
        let vc = ManSelectDateTimeVC(ts: model.ts)
        vc.modalPresentationStyle = .overCurrentContext
        vc.selectCallBack = {[weak self] ts, timeStr in
            guard let self = self else {
                return
            }
            self.model.ts = ts
            self.timeTF.text = timeStr
        }
        present(vc, animated: true)
    }


    @IBAction func selectPicHandle(_ sender: Any) {
        showPicPicker()
    }
    
    func showPicPicker()  {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action1 = UIAlertAction(title: "相机", style: .default) { _ in
            self.selectPhoto(type: .camera)
        }
        let action2 = UIAlertAction(title: "相册", style: .default) { _ in
            self.selectPhoto(type: .photoLibrary)
        }
        let action3 = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)
        present(alert, animated: true)
        
    }
    
    func selectPhoto(type: UIImagePickerController.SourceType)  {
        RXPermissionUtils.albumAndCamera(type: type) {[weak self] in
            guard let self = self else {
                return
            }
            let picker = UIImagePickerController()
            picker.sourceType = type
            picker.delegate = self
            picker.allowsEditing = false
            if #available(iOS 14.0, *) {
                picker.mediaTypes = [UTType.image.identifier]
            } else {
                // Fallback on earlier versions
                picker.mediaTypes = ["images"]
            }
            self.present(picker, animated: true)
        }
   
    }
    
    @IBAction func deleteHandle(_ sender: Any) {
        ManDataHelper.shared.delete(model: model)
        showHUDTextOnly("已删除") {[weak self] in
            guard let self = self else {
                return
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    
}


extension ManAddTicketVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        guard let img = info[.originalImage] as? UIImage else {
            return
        }
        let fileName = "\(Date().timeIntervalSince1970).jpg"
        CompressedHelper.shared.writeData(data: img.jpegData(compressionQuality: 0.5)!, fileName: fileName)
        picBtn.setImage(img, for: .normal)
        model.fileName = fileName
        
    }
    
    
}
